package com.bii.gelapp;

import java.io.ByteArrayOutputStream;

import org.opencv.android.Utils;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class DNAGaborActivity extends Activity {
	String analysisorigin = "";

	ImageView ivImage;
	public Bitmap originalBmp; // origin
	public Bitmap activeBmp; // edited image
	public Bitmap thresholdBmp;
	public Bitmap takenBmp;
	Button btPrev, btSegment, btSave, btFilter, btInverse;
	TextView tvThreshold, tvLambda, tvSigma;
	SeekBar sbThreshold, sbLambda, sbSigma;

	EditText etSigma;
	EditText etLambda;
	EditText etThreshold;

	int kernelSize = 24;
	// double sigma = 8;
	double sigma = 0;
	double theta = Math.PI / 2;
	// double lambda = 21;
	double lambda = 0;
	double gamma = 1;
	double psi = 1.5;

	public static int inverse = 1;
	public static int currentprogress;
	public static int thresholdvalue;
	public static int sigmavalue;
	public static int lambdavalue;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gaboractivity2);

		if (getIntent().hasExtra("analysisorigin")) {
			analysisorigin = getIntent().getStringExtra("analysisorigin");
		}

		LinearLayout myLayout = (LinearLayout) findViewById(R.id.gaboractivity2);
		myLayout.requestFocus();

		ivImage = (ImageView) findViewById(R.id.ivImage);
		try {
			originalBmp = InternalStorage.readBitmap(this, "gaussianBmp");
			activeBmp = originalBmp.copy(Config.ARGB_8888, true);
			ivImage.setImageBitmap(activeBmp);
			
			btSegment = (Button) findViewById(R.id.btSegment);
			btSave = (Button) findViewById(R.id.btSave);
			sbThreshold = (SeekBar) findViewById(R.id.sbThreshold);
			
			btPrev = (Button) findViewById(R.id.btPrev);
			btPrev.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					startActivity(new Intent(DNAGaborActivity.this,
							GaussianActivity.class));

				}
			});
			
			btInverse = (Button) findViewById(R.id.btInverse);
			btInverse.setEnabled(false);
			btInverse.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (inverse == 1) {
						inverse = 0;

					} else {
						inverse = 1;
					}
					if (takenBmp == null) {
						takenBmp = originalBmp.copy(Config.ARGB_8888, true);
					}
					else
					{
						takenBmp = activeBmp.copy(Config.ARGB_8888, true);
					}

					Mat srcImg = new Mat(takenBmp.getHeight(), takenBmp
							.getWidth(), CvType.CV_8U, new Scalar(4));
					Bitmap myBitmap32 = takenBmp.copy(Bitmap.Config.ARGB_8888,
							true);
					Utils.bitmapToMat(myBitmap32, srcImg);
					Imgproc.cvtColor(srcImg, srcImg, Imgproc.COLOR_BGR2GRAY);
					Mat thresholdMat = new Mat(takenBmp.getHeight(), takenBmp
							.getWidth(), CvType.CV_8U, new Scalar(4));
					if (inverse == 1) {
						Imgproc.threshold(srcImg, thresholdMat, thresholdvalue,
								255, Imgproc.THRESH_BINARY_INV);
					} else {
						Imgproc.threshold(srcImg, thresholdMat, thresholdvalue,
								255, Imgproc.THRESH_BINARY);
					}
					Bitmap thBmp = Bitmap.createBitmap(thresholdMat.cols(),
							thresholdMat.rows(), Bitmap.Config.ARGB_8888);
					Utils.matToBitmap(thresholdMat, thBmp);
					activeBmp = thBmp;
					ivImage.setImageBitmap(activeBmp);
					
				}
			});
			
			etLambda = (EditText) findViewById(R.id.etLambda);
			etLambda.setFilters(new InputFilter[] { new InputFilterMinMax("0",
					"100") });
			etLambda.setEnabled(false);
			etLambda.addTextChangedListener(new TextWatcher() {

				@Override
				public void onTextChanged(CharSequence s, int start,
						int before, int count) {
					// TODO Auto-generated method stub
					if (thresholdBmp == null) {
						if (takenBmp == null) {
							takenBmp = originalBmp.copy(Config.ARGB_8888, true);
						}
					} else {
						// if (takenBmp == null) {
						takenBmp = thresholdBmp.copy(Config.ARGB_8888, true);
						// }
					}
									
					int textLength = etLambda.getText().length();
					etLambda.setSelection(textLength, textLength);
					if (etLambda.getText().toString().equals("")) {
						currentprogress = 0;
					} else {
						currentprogress = Integer.parseInt(etLambda.getText()
								.toString());
					}

					lambdavalue = currentprogress;
					if (currentprogress != 0) {
						lambda = lambdavalue;
						Mat filtermat = new Mat(takenBmp.getHeight(),
								takenBmp.getWidth(), CvType.CV_8U);
						int ch = filtermat.channels();
						Utils.bitmapToMat(takenBmp, filtermat);
						Imgproc.cvtColor(filtermat, filtermat,
								Imgproc.COLOR_BGR2GRAY);

						ch = filtermat.channels();
						// result image below
						Mat resultImg = new Mat();
						// set gabor
						Mat gaborKernel = Imgproc.getGaborKernel(new Size(
								kernelSize, kernelSize), sigma,
								theta/* horizontal */, lambda, gamma, psi,
								CvType.CV_32F);

						ch = filtermat.channels();
						Imgproc.filter2D(filtermat, resultImg, -1, gaborKernel);

						ch = resultImg.channels();

						Bitmap filteredBmp = Bitmap.createBitmap(
								resultImg.cols(), resultImg.rows(),
								Bitmap.Config.ARGB_8888);
						Utils.matToBitmap(resultImg, filteredBmp);

						activeBmp = filteredBmp;
						ivImage.setImageBitmap(activeBmp);
					} else {
						ivImage.setImageBitmap(activeBmp);
						sbLambda.setProgress(lambdavalue);
					}

				}

				@Override
				public void beforeTextChanged(CharSequence s, int start,
						int count, int after) {
					// TODO Auto-generated method stub

				}

				@Override
				public void afterTextChanged(Editable s) {
					// TODO Auto-generated method stub

				}
			});
			
			sbLambda = (SeekBar) findViewById(R.id.sbLambda);
			// sbLambda.setProgress(21);
			sbLambda.setEnabled(false);
			sbLambda.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

				@Override
				public void onStopTrackingTouch(SeekBar seekBar) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onStartTrackingTouch(SeekBar seekBar) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onProgressChanged(SeekBar seekBar, int progress,
						boolean fromUser) {
					// TODO Auto-generated method stub
					if (thresholdBmp == null) {
						if (takenBmp == null) {
							takenBmp = originalBmp.copy(Config.ARGB_8888, true);
						}
					} else {
						takenBmp = thresholdBmp.copy(Config.ARGB_8888, true);
					}
					currentprogress = sbLambda.getProgress();
					lambdavalue = currentprogress;
					if (currentprogress != 0) {
						lambda = lambdavalue;
						Mat filtermat = new Mat(takenBmp.getHeight(),
								takenBmp.getWidth(), CvType.CV_8U);
						int ch = filtermat.channels();
						Utils.bitmapToMat(takenBmp, filtermat);
						Imgproc.cvtColor(filtermat, filtermat,
								Imgproc.COLOR_BGR2GRAY);

						ch = filtermat.channels();
						// result image below
						Mat resultImg = new Mat();
						// set gabor
						Mat gaborKernel = Imgproc.getGaborKernel(new Size(
								kernelSize, kernelSize), sigma,
								theta/* horizontal */, lambda, gamma, psi,
								CvType.CV_32F);

						ch = filtermat.channels();
						Imgproc.filter2D(filtermat, resultImg, -1, gaborKernel);

						ch = resultImg.channels();

						Bitmap filteredBmp = Bitmap.createBitmap(
								resultImg.cols(), resultImg.rows(),
								Bitmap.Config.ARGB_8888);
						Utils.matToBitmap(resultImg, filteredBmp);

						activeBmp = filteredBmp;
						ivImage.setImageBitmap(activeBmp);
						etLambda.setText("" + lambdavalue);
					} else {
						ivImage.setImageBitmap(activeBmp);
						etLambda.setText("" + lambdavalue);
					}
				}
			});
			
			etSigma = (EditText) findViewById(R.id.etSigma);
			etSigma.setFilters(new InputFilter[] { new InputFilterMinMax("0",
					"100") });
			etSigma.setEnabled(false);
			etSigma.addTextChangedListener(new TextWatcher() {

				@Override
				public void onTextChanged(CharSequence s, int start,
						int before, int count) {
					// TODO Auto-generated method stub
					if (thresholdBmp == null) {
						if (takenBmp == null) {
							takenBmp = originalBmp.copy(Config.ARGB_8888, true);
						}
					} else {
						// if (takenBmp == null) {
						takenBmp = thresholdBmp.copy(Config.ARGB_8888, true);
						// }
					}
						
					int textLength = etSigma.getText().length();
					etSigma.setSelection(textLength, textLength);
					if (etSigma.getText().toString().equals("")) {
						currentprogress = 0;
					} else {
						currentprogress = Integer.parseInt(etSigma.getText()
								.toString());
					}

					sigmavalue = currentprogress;
					if (currentprogress != 0) {
						sigma = sigmavalue;
						Mat filtermat = new Mat(takenBmp.getHeight(),
								takenBmp.getWidth(), CvType.CV_8U);
						int ch = filtermat.channels();
						Utils.bitmapToMat(takenBmp, filtermat);
						Imgproc.cvtColor(filtermat, filtermat,
								Imgproc.COLOR_BGR2GRAY);

						ch = filtermat.channels();
						// result image below
						Mat resultImg = new Mat();
						// set gabor
						Mat gaborKernel = Imgproc.getGaborKernel(new Size(
								kernelSize, kernelSize), sigma,
								theta/* horizontal */, lambda, gamma, psi,
								CvType.CV_32F);

						ch = filtermat.channels();
						Imgproc.filter2D(filtermat, resultImg, -1, gaborKernel);

						ch = resultImg.channels();

						Bitmap filteredBmp = Bitmap.createBitmap(
								resultImg.cols(), resultImg.rows(),
								Bitmap.Config.ARGB_8888);
						Utils.matToBitmap(resultImg, filteredBmp);

						activeBmp = filteredBmp;
						ivImage.setImageBitmap(activeBmp);
						
						sbSigma.setProgress(sigmavalue);

					} else {
						ivImage.setImageBitmap(activeBmp);
						sbSigma.setProgress(sigmavalue);
					}

				}

				@Override
				public void beforeTextChanged(CharSequence s, int start,
						int count, int after) {
					// TODO Auto-generated method stub

				}

				@Override
				public void afterTextChanged(Editable s) {
					// TODO Auto-generated method stub

				}
			});
			
			sbSigma = (SeekBar) findViewById(R.id.sbSigma);
			sbSigma.setEnabled(false);
			// sbLambda.setProgress(8);
			sbSigma.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

				@Override
				public void onStopTrackingTouch(SeekBar seekBar) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onStartTrackingTouch(SeekBar seekBar) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onProgressChanged(SeekBar seekBar, int progress,
						boolean fromUser) {
					// TODO Auto-generated method stub
					if (thresholdBmp == null) {
						if (takenBmp == null) {
							takenBmp = originalBmp.copy(Config.ARGB_8888, true);
						}
					} else {
						// if (takenBmp == null) {
						takenBmp = thresholdBmp.copy(Config.ARGB_8888, true);
						// }
					}
					currentprogress = sbSigma.getProgress();
					sigmavalue = currentprogress;
					if (currentprogress != 0) {
						sigma = sigmavalue;
						Mat filtermat = new Mat(takenBmp.getHeight(),
								takenBmp.getWidth(), CvType.CV_8U);
						int ch = filtermat.channels();
						Utils.bitmapToMat(takenBmp, filtermat);
						Imgproc.cvtColor(filtermat, filtermat,
								Imgproc.COLOR_BGR2GRAY);

						ch = filtermat.channels();
						// result image below
						Mat resultImg = new Mat();
						// set gabor
						Mat gaborKernel = Imgproc.getGaborKernel(new Size(
								kernelSize, kernelSize), sigma,
								theta/* horizontal */, lambda, gamma, psi,
								CvType.CV_32F);

						ch = filtermat.channels();
						Imgproc.filter2D(filtermat, resultImg, -1, gaborKernel);

						ch = resultImg.channels();

						Bitmap filteredBmp = Bitmap.createBitmap(
								resultImg.cols(), resultImg.rows(),
								Bitmap.Config.ARGB_8888);
						Utils.matToBitmap(resultImg, filteredBmp);

						activeBmp = filteredBmp;
						ivImage.setImageBitmap(activeBmp);
						etSigma.setText("" + sigmavalue);
						sbThreshold.setEnabled(true);
						btSegment.setEnabled(true);
						etThreshold.setEnabled(true);
					} else {
						ivImage.setImageBitmap(activeBmp);
						etSigma.setText("" + sigmavalue);
					}
				}
			});
			
			etThreshold = (EditText) findViewById(R.id.etThreshold);
			etThreshold.setFilters(new InputFilter[] { new InputFilterMinMax(
					"0", "255") });
			etThreshold.addTextChangedListener(new TextWatcher() {

				@Override
				public void onTextChanged(CharSequence s, int start,
						int before, int count) {
					
				}

				@Override
				public void beforeTextChanged(CharSequence s, int start,
						int count, int after) {
					// TODO Auto-generated method stub

				}

				@Override
				public void afterTextChanged(Editable s) {
					// TODO Auto-generated method stub
					// TODO Auto-generated method stub
					int textLength = etThreshold.getText().length();
					etThreshold.setSelection(textLength, textLength);

					int textLength1 = etThreshold.getText().length();
					etThreshold.setSelection(textLength1, textLength1);

					if (etThreshold.getText().toString().equals("")) {
						currentprogress = 0;
					} else {
						currentprogress = Integer.parseInt(etThreshold
								.getText().toString());
					}
					thresholdvalue = currentprogress;
					if (currentprogress > 0) {
						Mat srcImg = new Mat(originalBmp.getHeight(), originalBmp
								.getWidth(), CvType.CV_8U, new Scalar(4));
						Bitmap myBitmap32 = originalBmp.copy(
								Bitmap.Config.ARGB_8888, true);
						Utils.bitmapToMat(myBitmap32, srcImg);
						Imgproc.cvtColor(srcImg, srcImg, Imgproc.COLOR_BGR2GRAY);
						Mat thresholdMat = new Mat(originalBmp.getHeight(),
								originalBmp.getWidth(), CvType.CV_8U,
								new Scalar(4));
						if (inverse == 1) {
							Imgproc.threshold(srcImg, thresholdMat,
									thresholdvalue, 255,
									Imgproc.THRESH_BINARY_INV);
							inverse = 1;
						} else {
							Imgproc.threshold(srcImg, thresholdMat,
									thresholdvalue, 255, Imgproc.THRESH_BINARY);
							inverse = 0;
						}
						Bitmap thBmp = Bitmap.createBitmap(thresholdMat.cols(),
								thresholdMat.rows(), Bitmap.Config.ARGB_8888);
						Utils.matToBitmap(thresholdMat, thBmp);
						activeBmp = thBmp;
						thresholdBmp = thBmp;
						ivImage.setImageBitmap(activeBmp);
						btInverse.setEnabled(true);
						sbThreshold.setProgress(thresholdvalue);
						
					} else {
						ivImage.setImageBitmap(originalBmp);
						//etThreshold.setText(""+0);
						etThreshold.getText().clear();
						
						etSigma.getText().clear();
						//etSigma.setText(""+0);
						etSigma.setEnabled(false);
						etLambda.getText().clear();
						//etLambda.setText(""+0);
						etLambda.setEnabled(false);
						
						
						sbSigma.setProgress(0);
						sbSigma.setEnabled(false);
						sbLambda.setProgress(0);
						sbLambda.setEnabled(false);
					}
				}
			});

			sbThreshold
					.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

						@Override
						public void onStopTrackingTouch(SeekBar seekBar) {

						}

						@Override
						public void onStartTrackingTouch(SeekBar seekBar) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onProgressChanged(SeekBar seekBar,
								int progress, boolean fromUser) {

							currentprogress = sbThreshold.getProgress();
							thresholdvalue = currentprogress;
							if (currentprogress > 0) {
								Mat srcImg = new Mat(originalBmp.getHeight(),
										originalBmp.getWidth(), CvType.CV_8U,
										new Scalar(4));
								Bitmap myBitmap32 = originalBmp.copy(
										Bitmap.Config.ARGB_8888, true);
								Utils.bitmapToMat(myBitmap32, srcImg);
								Imgproc.cvtColor(srcImg, srcImg,
										Imgproc.COLOR_BGR2GRAY);
								Mat thresholdMat = new Mat(
										originalBmp.getHeight(), originalBmp
												.getWidth(), CvType.CV_8U,
										new Scalar(4));
								if (inverse == 1) {
									Imgproc.threshold(srcImg, thresholdMat,
											thresholdvalue, 255,
											Imgproc.THRESH_BINARY_INV);
									inverse = 1;
								} else {
									Imgproc.threshold(srcImg, thresholdMat,
											thresholdvalue, 255,
											Imgproc.THRESH_BINARY);
									inverse = 0;
								}
								Bitmap thBmp = Bitmap.createBitmap(
										thresholdMat.cols(),
										thresholdMat.rows(),
										Bitmap.Config.ARGB_8888);
								Utils.matToBitmap(thresholdMat, thBmp);
								activeBmp = thBmp;
								thresholdBmp = thBmp;
								ivImage.setImageBitmap(activeBmp);
								btInverse.setEnabled(true);
								etThreshold.setText("" + thresholdvalue);
								
								etSigma.setEnabled(true);
								etLambda.setEnabled(true);
								sbSigma.setEnabled(true);
								sbLambda.setEnabled(true);
								
							} else {
								ivImage.setImageBitmap(originalBmp);
								//etThreshold.setText(""+0);
								etThreshold.getText().clear();
								
								etSigma.getText().clear();
								//etSigma.setText(""+0);
								etSigma.setEnabled(false);
								etLambda.getText().clear();
								//etLambda.setText(""+0);
								etLambda.setEnabled(false);
								
								
								sbSigma.setProgress(0);
								sbSigma.setEnabled(false);
								sbLambda.setProgress(0);
								sbLambda.setEnabled(false);
							}
						}
					});
			
			//btSegment.setEnabled(false);
			btSegment.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (analysisorigin.equals("Protein")) {
						Intent goToNextActivity = new Intent(
								getApplicationContext(),
								SegmentationActivity.class);
						byte[] bytes;
						if (activeBmp == null) {
							bytes = compressImage(originalBmp);
						} else {
							bytes = compressImage(activeBmp);
						}
						goToNextActivity.putExtra("BMP", bytes);
						goToNextActivity.putExtra("analysisorigin", analysisorigin);
						startActivity(goToNextActivity);

					}
					else
					{
						Intent goToNextActivity = new Intent(
								getApplicationContext(),
								DNASegmentationActivity.class);
						byte[] bytes;
						if (activeBmp == null) {
							bytes = compressImage(originalBmp);
						} else {
							bytes = compressImage(activeBmp);
						}
						goToNextActivity.putExtra("BMP", bytes);
						goToNextActivity.putExtra("analysisorigin", analysisorigin);
						startActivity(goToNextActivity);
					}
				}
			});

		}
		catch(Exception e)
		{
			e.printStackTrace();
		}

	}

	public byte[] compressImage(Bitmap image) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.PNG, 0, stream);
		byte[] bytes = stream.toByteArray();
		return bytes;

	}

	public void invertedThreshold(Mat srcImg, Mat destImg, double thresh,
			double maxval) {
		for (int i = 0; i < srcImg.height(); i++) {
			for (int j = 0; j < srcImg.width(); j++) {
				double[] data = srcImg.get(i, j);
				if (data[0] > thresh)
					destImg.put(i, j, 0);
				else
					destImg.put(i, j, maxval);
			}
		}
	}
}


